package com.yjhb.android.sbz.activity;

import android.Manifest;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import androidx.viewpager.widget.ViewPager;

import com.bumptech.glide.Glide;
import com.jojo.android.zxlib.adapter.FragmentAdapter;
import com.jojo.android.zxlib.base.BaseFragment;
import com.jojo.android.zxlib.interfaces.Callback;
import com.jojo.android.zxlib.tool.Global;
import com.jojo.android.zxlib.tool.ZxLogTool;
import com.jojo.android.zxlib.tool.ZxToast;
import com.jojo.android.zxlib.tool.ZxTool;
import com.jojo.android.zxlib.view.bottombar.BottomBarItem;
import com.jojo.android.zxlib.view.bottombar.BottomBarLayout;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.tencent.imsdk.v2.V2TIMMessage;
import com.tencent.qcloud.tim.uikit.Observer;
import com.tencent.qcloud.tim.uikit.TUIKit;
import com.tencent.qcloud.tim.uikit.UnReadManager;
import com.tencent.qcloud.tim.uikit.base.IMEventListener;
import com.tencent.qcloud.tim.uikit.config.SysUserConfig;
import com.tencent.qcloud.tim.uikit.modules.message.MessageInfo;
import com.tencent.qcloud.tim.uikit.modules.message.MessageInfoUtil;
import com.umeng.analytics.MobclickAgent;
import com.umeng.commonsdk.UMConfigure;
import com.yjhb.android.sbz.App;
import com.yjhb.android.sbz.BuildConfig;
import com.yjhb.android.sbz.Conf;
import com.yjhb.android.sbz.R;
import com.yjhb.android.sbz.entity.UserInfo;
import com.yjhb.android.sbz.fragment.HallFragment;
import com.yjhb.android.sbz.fragment.HomeFragment;
import com.yjhb.android.sbz.fragment.InvitationFragment;
import com.yjhb.android.sbz.fragment.MyFragment;
import com.yjhb.android.sbz.manager.MsgNotificationManager;
import com.yjhb.android.sbz.manager.OAIDManager;
import com.yjhb.android.sbz.manager.ResManager;
import com.yjhb.android.sbz.manager.SysManager;
import com.yjhb.android.sbz.mvp.common.CommonPresenter;
import com.yjhb.android.sbz.mvp.main.MainPresenter;
import com.yjhb.android.sbz.mvp.main.MainView;
import com.yjhb.android.sbz.mvp.myinviter.MyInviterPresenter;
import com.yjhb.android.sbz.tool.AppUpdateTool;
import com.yjhb.android.sbz.tool.ChannelUtil;
import com.yjhb.android.sbz.tool.DataSaveTool;
import com.yjhb.android.sbz.tool.EventMsg;
import com.yjhb.android.sbz.tool.InvitationCodeTool;
import com.yjhb.android.sbz.tool.URLConfig;
import com.yjhb.android.sbz.v2.entity.VipConfig;
import com.yjhb.android.sbz.v2.fragment.V2GameFragment;
import com.yjhb.android.sbz.v2.mvp.presenter.VipConfigPresenter;
import com.yjhb.android.sbz.v2.mvp.view.VipConfigView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;


public class MainActivity extends BaseActivity<MainPresenter> implements ViewPager.OnPageChangeListener, MainView {
    @BindView(R.id.bottom_layout)
    BottomBarLayout bottomBarLayout;

    @BindView(R.id.viewpager)
    ViewPager viewpager;
    @BindView(R.id.bottom_mask)
    View bottom_mask;
    @BindView(R.id.bottom_layout_parent)
    View bottom_layout_parent;

    MyFragment myFragment;
    HallFragment hallFragment;
//    InvitationFragment invitationFragment;
    V2GameFragment gameFragment;
    HomeFragment homeFragment;
    List<BaseFragment> fragments = new ArrayList<>();
    FragmentAdapter adapter;

    private CommonPresenter commonPresenter;
    private MyInviterPresenter inviterPresenter;
    private VipConfigPresenter vipConfigPresenter;


    @Override
    protected MainPresenter initPresenter() {
        return new MainPresenter(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected boolean isImmerse() {
        return true;
    }

    @Override
    protected void initUI() {

        commonPresenter = new CommonPresenter(null);
        inviterPresenter = new MyInviterPresenter(null);
        vipConfigPresenter = new VipConfigPresenter(new VipConfigView() {
            @Override
            public void onVipConfig(@NotNull VipConfig vipConfig) {
                Global.getInstance().putCache("vipConfig", vipConfig);
            }

            @Override
            public void onFailure(int code, String msg) {

            }
        });
        initBottomBar();
        initFragment();
        bottomBarLayout.setViewPager(viewpager);
        requestPermissions();
        //初始化友盟
        initUM();
        InvitationCodeTool.getInvitationCode();
    }

    private void initFragment() {
        fragments.clear();
        fragments.add(homeFragment = new HomeFragment());
        fragments.add(hallFragment = new HallFragment());
//        fragments.add(invitationFragment = new InvitationFragment());
        fragments.add(gameFragment = new V2GameFragment());
        fragments.add(myFragment = new MyFragment());
        viewpager.setAdapter(adapter = new FragmentAdapter(getSupportFragmentManager(), fragments));
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (intent != null) {
            int index = intent.getIntExtra("selected", -1);
            if (index != -1) {
                bottomBarLayout.setCurrentItem(index);
            }
        }
        if (vipConfigPresenter != null) {
            vipConfigPresenter.getVipConfigList();
        }
        EventBus.getDefault().post(new EventMsg(EventMsg.USER_UPDATE_OK, null));
    }

    @Override
    protected void initData() {
        commonPresenter.updateUserInfo();
        //延时请求
        Global.getInstance().getMainHandler().postDelayed(new Runnable() {
            @Override
            public void run() {
                //版本信息
                new AppUpdateTool(MainActivity.this).check();
            }
        }, 500);

        //延时请求
        Global.getInstance().getMainHandler().postDelayed(new Runnable() {
            @Override
            public void run() {

                //初始化分享URL配置
                URLConfig.getInstance().init();
                //VIP配置信息
                vipConfigPresenter.getVipConfigList();
            }
        }, 1000);
    }

    @Override
    protected void regEvent() {
        //未读
        UnReadManager.getInstance().register(new Observer<Integer>() {
            @Override
            public void update(int type, Integer arg) {
                if (bottomBarLayout != null) {
                    int totalUnread = UnReadManager.getInstance().getUnreadMsg()
                            + UnReadManager.getInstance().getUncheck()
                            + UnReadManager.getInstance().getUnreadSys()
                            + UnReadManager.getInstance().getUnreadTask()
                            + UnReadManager.getInstance().getUnreadReport();
                    if (totalUnread < 100)
                        bottomBarLayout.setUnread(0, totalUnread);
                    else
                        bottomBarLayout.setUnread(0, 99);
                }
            }
        });
        //消息
        TUIKit.addIMEventListener(new IMEventListener() {
            @Override
            public void onForceOffline() {
                ZxToast.showINFOBottomToast("您的账号在别处登录。");
                SysManager.exitLogin(MainActivity.this);
            }

            @Override
            public void onNewMessage(V2TIMMessage v2TIMMessage) {
                super.onNewMessage(v2TIMMessage);
//                ZxToast.showINFOBottomToast("用户消息。");
                try {
                    String title = v2TIMMessage.getNickName();
                    if (TextUtils.isEmpty(title)) {
                        title = v2TIMMessage.getSender();
                    }
                    MessageInfo messageInfo = MessageInfoUtil.createMessageInfo(v2TIMMessage);
                    if (messageInfo.getMsgType() == MessageInfo.MSG_TYPE_CUSTOM) {
                        messageInfo.setExtra("【悬赏任务】");
                    }
                    MsgNotificationManager.sendNotification(getActivity(), 1, title, messageInfo.getExtra().toString());
                } catch (Exception e) {
                    ZxLogTool.err(e);
                }
            }

            @Override
            public void onSystemMessage(V2TIMMessage v2TIMMessage, SysUserConfig sysUserConfig) {
                super.onSystemMessage(v2TIMMessage, sysUserConfig);
//                ZxToast.showINFOBottomToast("系统消息。");
                try {
                    String title = "您有新的待处理消息";
                    MessageInfo messageInfo = MessageInfoUtil.createMessageInfo(v2TIMMessage);
                    switch (sysUserConfig) {
                        case REPORT_NOTICE:
                            UnReadManager.getInstance().setUnreadReport(UnReadManager.getInstance().getUnreadReport() + 1);
                            break;
                        case SYSTEM_NOTICE:
                            UnReadManager.getInstance().setUnreadSys(UnReadManager.getInstance().getUnreadSys() + 1);
                            break;
                        case CHECK_NOTICE:
                            UnReadManager.getInstance().setUncheck(UnReadManager.getInstance().getUncheck() + 1);
                            break;
                        case TASK_NOTICE:
                            UnReadManager.getInstance().setUnreadTask(UnReadManager.getInstance().getUnreadTask() + 1);
                            break;
                    }
                    MsgNotificationManager.sendNotification(getActivity(), 2, title, messageInfo.getExtra().toString());
                } catch (Exception e) {
                    ZxLogTool.err(e);
                }

            }
        });
        viewpager.addOnPageChangeListener(this);
        bottomBarLayout.setOnItemSelectedListener(new BottomBarLayout.OnItemSelectedListener() {
            @Override
            public void onItemSelected(BottomBarItem bottomBarItem, int previousPosition, int currentPosition) {
                if (previousPosition == 1 && currentPosition == 1) {
                    if (!ZxTool.isFastClick(2000)) {
                        EventBus.getDefault().post(new EventMsg(EventMsg.HALL_TOP_REFRESH, null));
                    }
                } else if (previousPosition == 0 && currentPosition == 0) {
                    if (!ZxTool.isFastClick(2000)) {
                        EventBus.getDefault().post(new EventMsg(EventMsg.HOME_TOP_REFRESH, null));
                    }
                }
            }
        });
//        bottomBarLayout.setOnItemClickListener(new BottomBarLayout.OnItemClickListener() {
//            @Override
//            public boolean onItemClick(BottomBarItem bottomBarItem, int previousPosition, int currentPosition) {
//                //点击游戏弹出界面，并拦截后续事件
//                if (currentPosition == 3) {
//                    if (!Tool.checkLogin(getActivity())) {
//                        return true;
//                    }
//                    return false;
//                }
//                return false;
//            }
//        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    private void initUM() {
        //用户同意隐私协议后再收集用户信息
        if (!DataSaveTool.isShowPrivacyTips()) {
            String channelName = ChannelUtil.INSTANCE.getApkChannelName(App.getInstance());
            ZxLogTool.e("channel:$channelName");
            UMConfigure.init(App.getInstance(), Conf.UM_APP_KEY, channelName, UMConfigure.DEVICE_TYPE_PHONE, "");
            UMConfigure.setLogEnabled(BuildConfig.LOG_DEBUG); // 日志启动
            MobclickAgent.setPageCollectionMode(MobclickAgent.PageMode.AUTO); //设置自动采集页面信息
        }

    }


    /*
            接收全局消息
         */
    @Subscribe
    public void onEventMsg(EventMsg eventMsg) {
        if (eventMsg.msg == EventMsg.USER_UPDATE_OK) {

        } else if (eventMsg.msg == EventMsg.REQUEST_USER_UPDATE) {
            if (commonPresenter != null)
                commonPresenter.updateUserInfo();
            if (vipConfigPresenter != null)
                vipConfigPresenter.getVipConfigList();
        } else if (eventMsg.msg == EventMsg.DISPLAY_BOTTOM_MASK) {
            bottom_layout_parent.setBackgroundResource(R.color.white);
            bottom_mask.setVisibility(View.VISIBLE);
        } else if (eventMsg.msg == EventMsg.HIDE_BOTTOM_MASK) {
            bottom_mask.setVisibility(View.GONE);
            bottom_layout_parent.setBackgroundResource(R.color.transparent);
        } else if (eventMsg.msg == EventMsg.REQUEST_MAIN_SWITCH_FRAGMENT) {
            bottomBarLayout.setCurrentItem((Integer) eventMsg.object);
        } else if (eventMsg.msg == EventMsg.REQUEST_BIND_INVITE_CODE) {
            Integer invite = Integer.parseInt(eventMsg.object.toString());
            if (invite != null) {
                inviterPresenter.bindMyInviter(invite);
            }
        }
    }


    /**
     * 初始化底部bar
     */
    private void initBottomBar() {
        bottomBarLayout.setOrientation(LinearLayout.HORIZONTAL);
        bottomBarLayout.addItem(createItem("首页", R.mipmap.index, R.mipmap.index_x));
        bottomBarLayout.addItem(createItem("悬赏大厅", R.mipmap.offer_a, R.mipmap.offer_x));
//        BottomBarItem item = createItem("邀请赚", R.mipmap.earn01, R.mipmap.earn01,
//                ResManager.dp() * 20, ResManager.dp() * 20);
//        item.getTextView().setVisibility(View.VISIBLE);
//        bottomBarLayout.addItem(item);
        bottomBarLayout.addItem(createItem("游戏赚钱", R.mipmap.news, R.mipmap.game_x));
        bottomBarLayout.addItem(createItem("我的", R.mipmap.my, R.mipmap.my_x));
//        int totalUnread = UnReadManager.getInstance().getUnreadMsg()
//                + UnReadManager.getInstance().getUncheck()
//                + UnReadManager.getInstance().getUnreadReport();
//        if (totalUnread < 100)
//            bottomBarLayout.setUnread(4, totalUnread);
//        else
//            bottomBarLayout.setUnread(4, 99);
    }


    /**
     * 创建底部item
     *
     * @param text
     * @param normalIcon
     * @param selectedIcon
     * @return
     */
    private BottomBarItem createItem(String text, int normalIcon, int selectedIcon) {
        BottomBarItem.Builder builder = new BottomBarItem.Builder(this);
        builder.marginTop(ZxTool.dp2px(6));
        builder.itemPadding(ZxTool.dp2px(5));
        builder.normalBg(new ColorDrawable(0));
        builder.iconHeight(ResManager.dp() * 16);
        builder.iconWidth(ResManager.dp() * 16);
        builder.titleTextSize(11);
        builder.titleNormalColor(R.color.black);
        builder.titleSelectedColor(R.color.colorPrimaryDark);
        return builder.create(normalIcon, selectedIcon, text);
    }

    private BottomBarItem createItem(String text, int normalIcon, int selectedIcon, int iconHeight, int iconWidth) {
        BottomBarItem.Builder builder = new BottomBarItem.Builder(this);
        builder.marginTop(ZxTool.dp2px(2));
        builder.itemPadding(ZxTool.dp2px(5));
        builder.normalBg(new ColorDrawable(0));
        builder.iconHeight(iconHeight);
        builder.iconWidth(iconWidth);
        builder.titleTextSize(11);
        builder.titleNormalColor(R.color.black);
        builder.titleSelectedColor(R.color.colorPrimaryDark);
        return builder.create(normalIcon, selectedIcon, text);
    }


    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {

    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }


    @Override
    public boolean doubleClickToExitSwitch() {
        return true;
    }

    /**
     * 权限
     */
    void requestPermissions() {
        RxPermissions permissions = new RxPermissions(this);
        permissions.request(Manifest.permission.READ_PHONE_STATE
                , Manifest.permission.READ_EXTERNAL_STORAGE
                , Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        OAIDManager.init(MainActivity.this)
                                .initOAID(new OAIDManager.AppIdsUpdater() {
                                    @Override
                                    public void onDeviceId(String ids) {

                                    }
                                });
                    }
                });
    }


    @Override
    public void onUserInfo(UserInfo userInfo) {

    }

    @Override
    public void onFailure(int code, String msg) {

    }

}